package com.zzyl.nursing.util;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @author: zhengsuyang
 * @Desc:
 * @create: 2025-10-10 21:11
 **/

public class AgeGenerator {
    /**
     * 根据身份证号计算年龄
     * @param idCardNo 身份证号码
     * @return 年龄
     */
    public static int getAgeByIdCard(String idCardNo) {
        if (idCardNo == null || idCardNo.length() != 18) {
            throw new IllegalArgumentException("无效的身份证号码");
        }

        // 提取出生日期（第7-14位）
        String birthDateStr = idCardNo.substring(6, 14);

        // 解析出生日期
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDate birthDate = LocalDate.parse(birthDateStr, formatter);

        // 计算年龄
        LocalDate currentDate = LocalDate.now();
        int age = currentDate.getYear() - birthDate.getYear();

        // 如果今年的生日还没到，年龄减1
        if (currentDate.getMonthValue() < birthDate.getMonthValue() ||
                (currentDate.getMonthValue() == birthDate.getMonthValue() &&
                        currentDate.getDayOfMonth() < birthDate.getDayOfMonth())) {
            age--;
        }

        return age;
    }
}
